//
//  CustomSheetView.swift
//  KoiAccounting
//
//  Created by 纪洪文 on 02.04.25.
//

import SwiftUI

struct CustomSheetView<Content: View>: View {
    @Environment(\.dismiss) private var dismiss
    @State private var sheetHeight: CGFloat = UIScreen.main.bounds.height
    @Binding var path: NavigationPath
    let content: () -> Content
    
    init(path: Binding<NavigationPath>, @ViewBuilder content: @escaping () -> Content) {
        self._path = path
        self.content = content
    }
    
    private var dismissThreshold: CGFloat {
        UIScreen.main.bounds.height * (3.0/4.0)
    }
    
    var body: some View {
        ZStack {
            content()
                .frame(maxWidth: .infinity, maxHeight: .infinity)
            
            // 现在手势识别器覆盖整个视图
            SheetGestureRepresentable(
                onDragChanged: { translation in
                    let newHeight = UIScreen.main.bounds.height - translation
                    sheetHeight = min(max(newHeight, UIScreen.main.bounds.height * 0.2), UIScreen.main.bounds.height)
                },
                onDragEnded: { velocity in
                    withAnimation(.interactiveSpring(response: 0.3, dampingFraction: 0.8)) {
                        if sheetHeight < dismissThreshold {
                            if !path.isEmpty {
                                path.removeLast()
                                sheetHeight = UIScreen.main.bounds.height
                            } else {
                                dismiss()
                            }
                        } else {
                            sheetHeight = UIScreen.main.bounds.height
                        }
                    }
                }
            )
        }
        .preference(key: SheetHeightKey.self, value: sheetHeight)
    }
}
